package com.itqiqi.api.tableapi.udf;

import com.itqiqi.api.pojo.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.types.Row;

public class UdfTest1_ScalarFunction {

    public static void main(String[] args) throws Exception {

        // 创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // 创建表环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 读取数据
        DataStreamSource<String> inputStream = env.readTextFile("input/sensor.txt");

        SingleOutputStreamOperator<SensorReading> dataStream = inputStream.map(new MapFunction<String, SensorReading>() {
            @Override
            public SensorReading map(String s) throws Exception {
                String[] words = s.split(",");
                return new SensorReading(words[0], new Long(words[1]), new Double(words[2]));
            }
        });

        // 将流转换成表
        Table sensorTable = tableEnv.fromDataStream(dataStream, "id, timestamp as ts, temperature as temp");

        // TODO: 2022/5/19 自定义标量函数，实现id的hash值
        // 在环境中注册UDF
        HashCode hashCode = new HashCode(23);
        tableEnv.registerFunction("hashcode", hashCode);

        // table API
        Table resTable = sensorTable.select("id, ts, hashcode(id)");

        // SQL
        tableEnv.createTemporaryView("sensorTable", sensorTable);
        Table sqlTable = tableEnv.sqlQuery("select id, ts, hashcode(id) from sensorTable");

        // 输出结果
        sensorTable.printSchema();
        tableEnv.toAppendStream(resTable, Row.class).print("resTable");
        tableEnv.toAppendStream(sqlTable, Row.class).print("sqlTable");

        env.execute();
    }

    // TODO: 2022/5/19 实现自定义的Scalar Function
    public static class HashCode extends ScalarFunction{

        private int factor = 13;

        public HashCode(int factor) {
            this.factor = factor;
        }

        public int eval(String s) {
            return s.hashCode() * factor;
        }
    }
}
